/**
 * https://leetcode.cn/problems/find-k-pairs-with-smallest-sums/submissions/590070869/
 * 373.查找和最小的k对数字
 * medium 2024.12.29
 * 优先队列
 */

class Solution {
public:
    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        auto cmp = [&nums1, &nums2](const pair<int, int> & a, const pair<int, int> & b) {
            return nums1[a.first] + nums2[a.second] > nums1[b.first] + nums2[b.second];
        };
        int n = nums1.size();
        int m = nums2.size();
        vector<vector<int>> arr;
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q(cmp);
        for (int i = 0; i < min(k, n); i++) {
            q.emplace(i, 0);
        }
        while (k--&&!q.empty()) {
            auto [x, y] = q.top(); 
            q.pop();
            arr.push_back({nums1[x], nums2[y]});
            if (y+1<m) {
                q.emplace(x, y + 1);
            }
        }
        return arr;
    }
};